﻿using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace VisionBasicSystem.Commons
{
    /// <summary>
    /// 工具类
    /// </summary>
    internal class Utils
    {
        /// <summary>
        /// 给字符串补齐位数
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string PolishingStrData(string data)
        {
            string NewData = "";

            if (data.Contains("-"))
            {
                string NewData1 = data.Replace("-", "");
                string NewData2 = NewData1.PadLeft(6, '0');
                NewData = "-" + NewData2;
            }
            else
            {
                NewData = data.PadLeft(7, '0');
            }

            return NewData;
        }

        //获取路径
        public static string GetImagePath()
        {
            string personImgPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + Path.DirectorySeparatorChar.ToString();
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }
            return personImgPath;
        }

        //字符串转16进制字节数组
        public static byte[] StrToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        // 把字节型转换成十六进制字符串
        public static String ByteToChar(uint length, byte[] data)
        {
            StringBuilder stringbuiler = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                String temp = data[i].ToString("x");
                if (temp.Length == 1)
                {
                    stringbuiler.Append("0" + temp);
                }
                else
                {
                    stringbuiler.Append(temp);
                }
            }
            return (stringbuiler.ToString());
        }

        //Http
        public static string Postdata(string jsonStr, string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "application/json";
            request.ContentType = "application/json";
            //如果是get方式就不用一下using内代码，将参数在url中发送
            using (Stream outStream = request.GetRequestStream())
            {
                StreamWriter sw = new StreamWriter(outStream);
                sw.WriteLine(jsonStr);
                sw.Flush();
                sw.Close();
            }
            //获取服务器端response的json请求
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream inStream = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(inStream);
                string resJson = sr.ReadToEnd();
                return resJson;
            }
        }

        /// <summary>
        /// 字节流转换成图片
        /// </summary>
        /// <param name="byt">要转换的字节流</param>
        /// <returns>转换得到的Image对象</returns>
        public static Image BytToImg(byte[] byt)
        {
            MemoryStream ms = new MemoryStream(byt);
            Image img = Image.FromStream(ms);
            return img;
        }

        /// <summary>
        /// 根据图片路径返回图片的字节流byte[]
        /// </summary>
        /// <param name="imagePath">图片路径</param>
        /// <returns>返回的字节流</returns>
        public static byte[] GetImageByte(string imagePath)
        {
            FileStream files = new FileStream(imagePath, FileMode.Open);
            byte[] imgByte = new byte[files.Length];
            files.Read(imgByte, 0, imgByte.Length);
            files.Close();
            return imgByte;
        }

        /// 无损压缩图片
        /// <param name="sFile">原图片</param>
        /// <param name="dFile">压缩后保存位置</param>
        /// <param name="dHeight">高度</param>
        /// <param name="dWidth"></param>
        /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param>
        /// <returns></returns>
        public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
        {
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int sW = 0, sH = 0;

            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);

            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();
            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }

        /// <summary>
        /// 变成黑白图
        /// </summary>
        /// <param name="bmp">原始图</param>
        /// <param name="mode">模式。0:加权平均  1:算数平均</param>
        /// <returns></returns>
        public static Bitmap ToGray(Bitmap bmp, int mode)
        {
            if (bmp == null)
            {
                return null;
            }
            int w = bmp.Width;
            int h = bmp.Height;
            try
            {
                byte newColor = 0;
                BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                unsafe
                {
                    byte* p = (byte*)srcData.Scan0.ToPointer();
                    for (int y = 0; y < h; y++)
                    {
                        for (int x = 0; x < w; x++)
                        {
                            if (mode == 0) // 加权平均
                            {
                                newColor = (byte)((float)p[0] * 0.114f + (float)p[1] * 0.587f + (float)p[2] * 0.299f);
                            }
                            else    // 算数平均
                            {
                                newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f);
                            }
                            p[0] = newColor;
                            p[1] = newColor;
                            p[2] = newColor;

                            p += 3;
                        }
                        p += srcData.Stride - w * 3;
                    }
                    bmp.UnlockBits(srcData);
                    return bmp;
                }
            }
            catch
            {
                return null;
            }
        }

        public static float ToFloat(byte[] data)
        {
            float a = 0;
            byte i;
            byte[] x = data;
            unsafe
            {
                void* pf;
                fixed (byte* px = x)
                {
                    pf = &a;
                    for (i = 0; i < data.Length; i++)
                    {
                        *((byte*)pf + i) = *(px + i);
                    }
                }
            }

            return a;
        }

        public static byte[] ToByte(float data)
        {
            unsafe
            {
                byte* pdata = (byte*)&data;
                byte[] byteArray = new byte[sizeof(float)];
                for (int i = 0; i < sizeof(float); ++i)
                    byteArray[i] = *pdata++;

                return byteArray;
            }
        }

        public byte[] CreateWriteCmdReg(string SlaveAddress, string Funtion, string StartAddress, string DataNumber, string ByteNumber, string Data)
        {
            try
            {
                byte[] SlaveAddressBuff = StringToHex(SlaveAddress);
                byte[] FuntionBuff = StringToHex(Funtion);
                byte[] StartAddressBuff = StringToHex(StartAddress);
                byte[] DataNumberBuff = StringToHex(DataNumber);
                byte[] ByteNumberBuff = StringToHex(ByteNumber);
                byte[] DataBuff = StringToHex(Data);

                byte[] returnVal = new byte[DataBuff.Length + 9];
                returnVal[0] = SlaveAddressBuff[0];
                returnVal[1] = FuntionBuff[0];
                returnVal[2] = StartAddressBuff[0];
                returnVal[3] = StartAddressBuff[1];
                returnVal[4] = DataNumberBuff[0];
                returnVal[5] = DataNumberBuff[1];
                returnVal[6] = ByteNumberBuff[0];

                for (int i = 0; i < DataBuff.Length; i++)
                {
                    returnVal[i + 7] = DataBuff[i];
                }
                int length = DataBuff.Length + 7;
                byte[] cmdData = new byte[length];
                for (int i = 0; i < length; i++)
                {
                    cmdData[i] = returnVal[i];
                }

                //byte[] CrcBuff = CRC_Chk(cmdData);
                //returnVal[length] = CrcBuff[0];
                //returnVal[length + 1] = CrcBuff[1];

                return returnVal;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 转换成为16进制
        /// </summary>
        /// <param name="mString"></param>
        /// <returns></returns>
        private byte[] StringToHex(string mString)
        {
            byte[] mHex = new byte[mString.Length / 2];
            try
            {
                for (int i = 0; i < mString.Length / 2; i++)
                {
                    mHex[i] = Convert.ToByte(mString.Substring(i * 2, 2), 16);
                }
                return mHex;
            }
            catch (Exception)
            {
                return mHex;
            }
        }

        public byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
            {
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            }

            return buffer;
        }

        /// <summary>
        /// byte[] 数组转换成HEXString
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
            {
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }
            return sb.ToString().ToUpper();
        }
    }
}